<?php

/**
 * 运营商审核退换货
 */

namespace app\home\controller;
use think\Lang;
use think\Db;
/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Sellerreview extends BaseSeller {

    public function _initialize() {
        parent::_initialize();
        Lang::load(APP_PATH . 'home/lang/'.config('default_lang').'/sellerreturn.lang.php');
        //向模板页面输出退款退货状态
        $this->getRefundStateArray();
    }

    /**
     * 退货记录列表页
     *
     */
    public function index() {
        $refundreturn_model = model('refundreturn');
        $condition = array();
        // $condition['store_id'] = session('store_id');
        $condition['yys_id'] = session('store_id');
        $return_type = [
             '0' => 2,
             '1' => 3
        ];
        $condition['refund_type'] = ['in',$return_type];//类型:1为退款,2为退货,3为换货
        $keyword_type = array('order_sn', 'refund_sn', 'buyer_name');

        $keyword = input('get.keyword');
        $type = input('get.type');
        if (trim($keyword) != '' && in_array($type, $keyword_type)) {
            $condition[$type] = array('like', '%' . $keyword . '%');
        }
        $add_time_from = input('get.add_time_from');
        $add_time_to = input('get.add_time_to');
        if (trim($add_time_from) != '' || trim($add_time_to) != '') {
            $add_time_from = strtotime(trim($add_time_from));
            $add_time_to = strtotime(trim($add_time_to));
            if ($add_time_from !== false || $add_time_to !== false) {
                $condition['add_time'] = array('between', array($add_time_from, $add_time_to));
            }
        }
        $seller_state = intval(input('get.state'));
        if ($seller_state > 0) {
            $condition['seller_state'] = $seller_state;
        }
        // $order_lock = intval(input('param.lock'));
        // if ($order_lock != 1) {
        //     $order_lock = 2;
        // }
        // $condition['order_lock'] = $order_lock;
        $return_list = $refundreturn_model->getReturnList($condition, 10);

        $this->assign('return_list', $return_list);
        //分页
        $show_page = $refundreturn_model->page_info->render();
        $this->assign('show_page', $show_page);

        /* 设置卖家当前菜单  */
        $this->setSellerCurMenu('sellerreview');
        /* 设置卖家当前栏目 */
        $state = input('state');
        if (!in_array($state, array('deliverno', 'delivering', 'delivered'))) {
            $state = 'deliverno';
        }
        $this->setSellerCurItem($state);

        return $this->fetch($this->template_dir.'index');
    }

    /**
     * 退货审核页
     */
    public function edit() {
        $refundreturn_model = model('refundreturn');
        $condition = array();
        // $condition['store_id'] = session('store_id');
        $condition['yys_id'] = session('store_id');
        $condition['refund_id'] = intval(input('param.return_id'));
        $return_list = $refundreturn_model->getReturnList($condition);
        $return = $return_list[0];
        if (!request()->isPost()) {
            $this->assign('return', $return);
            $info['buyer'] = array();
            // if (!empty($return['pic_info'])) {
            //     $info = unserialize($return['pic_info']);
            // }
//            $this->assign('pic_list', $info['buyer']);
            $this->assign('pic_list', '');
            $member_model = model('member');
            $member = $member_model->getMemberInfoByID($return['buyer_id']);
            $this->assign('member', $member);
            $condition = array();
            $condition['order_id'] = $return['order_id'];
            $order = $refundreturn_model->getRightOrderList($condition, $return['order_goods_id']);
            $this->assign('order', $order);
            $this->assign('store', $order['extend_store']);
            $this->assign('order_common', $order['extend_order_common']);
            $this->assign('goods_list', $order['goods_list']);

            //获取图片
            $apply_images = json_decode($return['pic_info'],true);
            $this->assign('apply_images', $apply_images);
            $config = db('config')->where('code', 'qiniu_http')->find();
            $this->assign('http_name', $config['value']);

            /* 设置卖家当前菜单 */
            $this->setSellerCurMenu('sellerreview');
            /* 设置卖家当前栏目 */
            $state = input('state');
            if (!in_array($state, array('deliverno', 'delivering', 'delivered'))) {
                $state = 'deliverno';
            }
            
            $this->setSellerCurItem($state);
            return $this->fetch($this->template_dir.'edit');
        } else {
            if ($return['seller_state'] != '1') {
                ds_json_encode(10001,lang('wrong_argument'));
            }
            $order_id = $return['order_id'];
            $refund_array = array();
            $refund_array['seller_time'] = time();
            $refund_array['seller_state'] = input('post.seller_state'); //卖家处理状态:1为待审核,2为同意,3为不同意
            $refund_array['seller_message'] = input('post.seller_message');

            //退款 退货  换货 都需要退货
            if ($refund_array['seller_state'] == '2') {
                //同意的话  退货
                $refund_array['return_type'] = '2'; //退货类型:1为不用退货,2为需要退货
                $refund_array['refund_state'] = '2'; //'申请状态:1:处理中,2:待管理员处理,3:已完成',

                //运营商同意退换货之后前台就不可以取消
                if($return['refund_type'] == 2){
                    //退货 0--无退换货操作 1--退款操作 2--正在退货 3--正在换货 4--退货成功 5--评价成功 6--退款成功 7--供应商处理换货成功 8--运营商处理退货成功 9--运营商处理换货成功
                    db('ordergoods')->where(['rec_id'=>$return['order_goods_id']])->update(['return_status'=>8]);

                    //添加订单日志  同意退货
                    $data = array();
                    $data['order_id'] = $order_id;
                    $data['log_role'] = 'seller';
                    $data['log_msg'] = '处理状态为同意退货';
                    $data['log_user'] = session('seller_name');
                    $data['log_orderstate'] = 30;
                    model('order')->addOrderlog($data);
                }else if($return['refund_type'] == 3){
                    db('ordergoods')->where(['rec_id'=>$return['order_goods_id']])->update(['return_status'=>9]);

                    //添加订单日志  同意换货
                    $data = array();
                    $data['order_id'] = $order_id;
                    $data['log_role'] = 'seller';
                    $data['log_msg'] = '处理状态为同意换货';
                    $data['log_user'] = session('seller_name');
                    $data['log_orderstate'] = 30;
                    model('order')->addOrderlog($data);
                }
            } elseif ($refund_array['seller_state'] == '3') {
                //不同意的话 状态已完成
                $refund_array['refund_state'] = '3'; //状态:1为处理中,2为待管理员处理,3为已完成

                //不同意的话，找到这条记录，判断原来return_status是什么状态，再改回去什么状态
                 $order_goods_info = db('ordergoods')->find($return['order_goods_id']);
                 
                 #判断当前商品是否是正在退换货的商品，如果是第一次提交的话，不同意情况下，状态为0，其他情况还是原来的值
                 $return_status = $order_goods_info['return_status'];
                 if($order_goods_info['return_status'] == 2 || $order_goods_info['return_status'] == 3){
                    $return_status = 0;
                 }

                //修改状态 refund_type
                 if($return['refund_type'] == 2){

                    $fail_status = 2; #退货失败
                    //如果换货也失败了，
                    if($order_goods_info['fail_status'] == 3){
                        $fail_status = 4; #全部失败，前端不能再操作退换货
                    }
   
                     //退货
                    db('ordergoods')->where(['rec_id'=>$return['order_goods_id']])->update(['fail_status'=>$fail_status,'return_status'=>$return_status]);//状态:0：无操作 1：退款失败 2：退货失败 3：换货失败
                    
                    //添加订单日志  拒绝退货
                    $data = array();
                    $data['order_id'] = $order_id;
                    $data['log_role'] = 'seller';
                    $data['log_msg'] = '处理状态为拒绝退货';
                    $data['log_user'] = session('seller_name');
                    $data['log_orderstate'] = 30;
                    model('order')->addOrderlog($data);
                 }else if($return['refund_type'] == 3){
                    $fail_status = 3; #退货失败
                    //如果退货也失败了，
                    if($order_goods_info['fail_status'] == 2){
                        $fail_status = 4; #全部失败，前端不能再操作退换货
                    }
                    //换货
                    db('ordergoods')->where(['rec_id'=>$return['order_goods_id']])->update(['fail_status'=>$fail_status,'return_status'=>$return_status]);//状态:0：无操作 1：退款失败 2：退货失败 3：换货失败

                    //添加订单日志  拒绝换货
                    $data = array();
                    $data['order_id'] = $order_id;
                    $data['log_role'] = 'seller';
                    $data['log_msg'] = '处理状态为拒绝换货';
                    $data['log_user'] = session('seller_name');
                    $data['log_orderstate'] = 30;
                    model('order')->addOrderlog($data);
                 }

            } else {
                $refund_array['seller_state'] = '2';  //'卖家处理状态:1:待审核,2:同意,3:不同意',
                $refund_array['refund_state'] = '2';  //'申请状态:1:处理中,2:待管理员处理,3:已完成',
                $refund_array['return_type'] = '2'; //退货类型:1为不用退货,2为需要退货
            }
            $state = $refundreturn_model->editRefundreturn($condition, $refund_array);
            if ($state) {
                #根据运营商审核的状态，给客户推送消息 
                $member_info = db('member')
                    ->where(['member_id' => $return['buyer_id']])
                    ->find();

                #通知内容
                $notif_data = [
                    'order_id' => $order_id,
                    'notif_title' =>  $return['refund_type'] == 2 ? '退货' : '换货' . '通知',
                    'notif_content' =>  '提交的申请已审核，审核备注：' . $refund_array['seller_message'],
                    'member_id' => $member_info['member_id'],
                    'member_name' => $member_info['member_name'],
                ];
                model('points')->saveAfficeslog(0, 0, $notif_data); #客户
                if($refund_array['seller_state'] == 2){
                    #同意的话，供应商发，
                    model('points')->saveAfficeslog(0, 3, $notif_data); #供应商
                }
                #推送
                pushMessageToSingle('通知', $member_info['clientid'], '您提交的申请已审核，请及时查看！');
                #end

                if ($refund_array['seller_state'] == '3' && $return['order_lock'] == '2') {
                    $refundreturn_model->editOrderUnlock($order_id); //订单解锁
                }
                $this->recordSellerlog(lang('any_returns') . $return['refund_sn']);

                // 发送买家消息
                $param = array();
                $param['code'] = 'refund_return_notice';
                $param['member_id'] = $return['buyer_id'];
                $param['param'] = array(
                    'refund_url' => url('Memberreturn/view', ['return_id' => $return['refund_id']]),
                    'refund_sn' => $return['refund_sn']
                );
                \mall\queue\QueueClient::push('sendMemberMsg', $param);
                ds_json_encode(10000,lang('ds_common_save_succ'));
            } else {
                ds_json_encode(10001,lang('ds_common_save_fail'));
            }
        }
    }

    /**
     * 退货记录查看页
     *
     */
    public function view() {
        $refundreturn_model = model('refundreturn');
        $condition = array();
        // $condition['store_id'] = session('store_id');
        $condition['yys_id'] = session('store_id');
        $condition['refund_id'] = intval(input('param.return_id'));
        $return_list = $refundreturn_model->getReturnList($condition);

        $return = $return_list[0];
        $this->assign('return', $return);
        $express_list = rkcache('express', true);
        if ($return['express_id'] > 0 && !empty($return['invoice_no'])) {
            $this->assign('express_name', $express_list[$return['express_id']]['express_name']);
            $this->assign('express_code', $express_list[$return['express_id']]['express_code']);
        }
//        $info['buyer'] = array();
//        if (!empty($return['pic_info'])) {
//            $info = unserialize($return['pic_info']);
//        }
//        $this->assign('pic_list', $info['buyer']);
        $this->assign('pic_list', '');
        $member_model = model('member');
        $member = $member_model->getMemberInfoByID($return['buyer_id']);
        $this->assign('member', $member);
        $condition = array();
        $condition['order_id'] = $return['order_id'];
        $order = $refundreturn_model->getRightOrderList($condition, $return['order_goods_id']);
        $this->assign('order', $order);
        $this->assign('store', $order['extend_store']);
        $this->assign('order_common', $order['extend_order_common']);
        $this->assign('goods_list', $order['goods_list']);
        /* 设置卖家当前菜单 */
        $this->setSellerCurMenu('sellerreview');
        /* 设置卖家当前栏目 */
        $state = input('state');
        if (!in_array($state, array('deliverno', 'delivering', 'delivered'))) {
            $state = 'deliverno';
        }
        //获取图片
        $apply_images = json_decode($return['pic_info'],true);
        $this->assign('apply_images', $apply_images);
        $config = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $config['value']);
        $this->setSellerCurItem($state);
        return $this->fetch($this->template_dir.'view');
    }


    function getRefundStateArray($type = 'all') {
        $state_array = array(
            '1' => lang('refund_state_confirm'),
            '2' => lang('refund_state_yes'),
            '3' => lang('refund_state_no')
        ); //卖家处理状态:1为待审核,2为同意,3为不同意
        $this->assign('state_array', $state_array);

        $type_array = array(
            '1' => '退款',
            '2' => '退货',
            '3' => '换货'
        ); //卖家处理状态:1为待审核,2为同意,3为不同意
        $this->assign('type_array', $type_array);

        $admin_array = array(
            '1' => lang('in_processing'),
            '2' => lang('to_processed'),
            '3' => '已完成',
        ); //确认状态:1为买家或卖家处理中,2为待平台管理员处理,3为退款退货已完成
        $this->assign('admin_array', $admin_array);

        //供应商状态
        $supply_array = array(
            '1' => '待收货',
            '2' => '待收货',
            '3' => '待收货',
            '4' => '已确认收货',
            '5' => '已再次发货',
        ); 
        $this->assign('supply_array', $supply_array);

        $state_data = array(
            'seller' => $state_array,
            'admin' => $admin_array
        );
        if ($type == 'all') {
            return $state_data; //返回所有
        }
        return $state_data[$type];
    }

    /**
     * 用户中心右边，小导航
     *
     * @param string	$menu_type	导航类型
     * @param string 	$name	当前导航的name
     * @return
     */
    protected function getSellerItemList()
    {
        $menu_array = array();
        $menu_type=request()->action();
        switch ($menu_type) {
            case 'index':
                $menu_array = array(
                    array('name' => 'deliverno', 'text' => '退换货列表', 'url' => url('Sellerreview/index')),
                    // array('name' => 'delivering', 'text' => lang('ds_member_path_delivering'),  'url' => url('Sellerdeliver/index','state=delivering')),
                    // array('name' => 'delivered', 'text' => lang('ds_member_path_delivered'), 'url' => url('Sellerdeliver/index','state=delivered')),
                );
                break;
            case 'search':
                $menu_array = array(
                     array('name' => 'nodeliver', 'text' => lang('ds_member_path_deliverno'), 'url' => url('Sellerdeliver/index/state/nodeliver')),
                     array('name' => 'delivering', 'text' => lang('ds_member_path_delivering'), 'url' => url('Sellerdeliver/index/state/delivering')),
                     array('name' => 'delivered', 'text' => lang('ds_member_path_delivered'), 'url' => url('Sellerdeliver/index/state/delivered')),
                     array('name' => 'search', 'text' => lang('ds_member_path_deliver_info'), 'url' => '###'),
                );
                break;
        }
        return $menu_array;
    }

}
